using static AnalyStock.DataManage.HttpClientUtility;

namespace AnalyStock.DataManage;
/// <summary>
/// 腾讯数据接口，主要提取当日交易数据和分时交易数据   
/// </summary>
public class UtilityOfTencent
{
    private enum DownDataType
    {
        FinancialIndex, CurrentDailyData, CurrentMinuteData, HistoryData
    }
    //"51~五 粮 液~000858~27.78~27.60~27.70~417909~190109~227800~27.78~492~27.77~332~27.76~202~27.75~334~27.74~291~27.79~305~27.80~570~27.81~269~27.82~448~27.83~127~15:00:13/27.78/4365/S/12124331/24602|14:56:55/27.80/14/S/38932/24395|14:56:52/27.81/116/B/322585/24392|14:56:49/27.80/131/S/364220/24385|14:56:46/27.81/5/B/13905/24381|14:56:43/27.80/31/B/86199/24375~20121221150355~0.18~0.65~28.11~27.55~27.80/413544/1151265041~417909~116339~1.10~10.14~~28.11~27.55~2.03~1054.39~1054.52~3.64~30.36~24.84~";
    // 以 ~分割字符串中内容，下标从0开始，依次为
    //  0: 未知  1: 名字  2: 代码  3: 当前价格  4: 昨收  5: 今开  6: 成交量（手）  7: 外盘  8: 内盘   30: 时间
    // 31: 涨跌 32: 涨跌% 33: 最高 34: 最低 35: 价格/成交量（手）/成交额 36: 成交量（手） 37: 成交额（万） 38: 换手率 39: 市盈率
    // 40:  41: 最高 42: 最低 43: 振幅 44: 流通市值 45: 总市值 46: 市净率 47: 涨停价 48: 跌停价
    public static async Task<DailyOfTencent> GetTodayTradeData(string stockcode)
    {
        var uri = SeleUriAddress(DownDataType.CurrentDailyData, stockcode);
        var result = await HttpClientGetAsync(uri).ConfigureAwait(false);
        if (result == null || result.Length < 4) throw new Exception(result);
        var currDaily = result.Split("~");
        return new DailyOfTencent
        {
            Name = currDaily[1],
            Stockcode = currDaily[2],
            Close = currDaily[3].ConvertToFloat(),
            YestClose = currDaily[4].ConvertToFloat(),
            Open = currDaily[5].ConvertToFloat(),
            Date = currDaily[30],
            High = currDaily[33].ConvertToFloat(),
            Low = currDaily[34].ConvertToFloat(),
            Vol = currDaily[37].ConvertToFloat(),
            Amount = currDaily[38].ConvertToFloat(),
            Change = currDaily[31].ConvertToFloat(),
            Pct_chg = currDaily[32].ConvertToFloat(),
        };

    }
    /// <summary>
    ///     当日在线分时
    /// </summary>
    /// <param name="stockCode"></param>
    /// <returns></returns>
    public static async Task<MinuteOfTencent> GetMintueTradeData(string stockCode)
    {
        //深圳 1 沪市6              
        var uri = SeleUriAddress(DownDataType.CurrentMinuteData, stockCode);
        var result = await HttpClientGetAsync(uri).ConfigureAwait(false);
        var startStr =
            $"\"{(stockCode.StartsWith("6") ? "sh" : "sz")}{stockCode[..6]}\":{{\"data\":";
        var endStr = ",\"qt\":{";
        var josntxtRange = new Range(result.IndexOf(startStr) + startStr.Length,
                                     result.IndexOf(endStr));
        //没有获得分时数据，抛出异常
        if (result == null || result[josntxtRange].Length < 45) throw new Exception(result);
        var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
        return JsonSerializer.Deserialize<MinuteOfTencent>(result[josntxtRange], options);
    }

    // param string stockcode, string startdate,string enddate
    private static Uri SeleUriAddress(DownDataType downType, string stockCode)
    {
        var codeOfMarket = (stockCode.StartsWith("6") ? "sh" : "sz") + stockCode[..6];
        return new Uri(
            downType switch
            {
                DownDataType.CurrentDailyData => $"http://qt.gtimg.cn/q={codeOfMarket}",
                DownDataType.CurrentMinuteData => $"https://web.ifzq.gtimg.cn/appstock/app/minute/query?code={codeOfMarket}",
                _ => throw new NotImplementedException()
            });
    }

}